import {storage} from '@/config'
import cookie from 'js-cookie'

/**
 * @description 获取token
 * @param key 缓存键值
 * @returns {string|ActiveX.IXMLDOMNode|Promise<any>|any|IDBRequest<any>|MediaKeyStatus|FormDataEntryValue|Function|Promise<Credential | null>}
 */
export function getToken(key: string) {
  if (storage) {
    if ('localStorage' === storage) {
      return localStorage.getItem(key)
    } else if ('sessionStorage' === storage) {
      return sessionStorage.getItem(key)
    } else if ('cookie' === storage) {
      return cookie.get(key)
    } else {
      return localStorage.getItem(key)
    }
  } else {
    return localStorage.getItem(key)
  }
}

/**
 * @description 存储token
 * @param token 值
 * @param key 缓存键值
 * @returns {void|*}
 */
export function setToken(token: string, key: string) {
  if (storage) {
    if ('localStorage' === storage) {
      return localStorage.setItem(key, token)
    } else if ('sessionStorage' === storage) {
      return sessionStorage.setItem(key, token)
    } else if ('cookie' === storage) {
      return cookie.set(key, token)
    } else {
      return localStorage.setItem(key, token)
    }
  } else {
    return localStorage.setItem(key, token)
  }
}

/**
 * @description 移除token
 * @param key 缓存键值
 * @returns {void|Promise<void>}
 */
export function removeToken(key: string) {
  if (storage) {
    if ('localStorage' === storage) {
      return localStorage.removeItem(key)
    } else if ('sessionStorage' === storage) {
      return sessionStorage.clear()
    } else if ('cookie' === storage) {
      return cookie.remove(key)
    } else {
      return localStorage.removeItem(key)
    }
  } else {
    return localStorage.removeItem(key)
  }
}
